package front

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	daoFront "hft/Http/Models/dao/front"
	"hft/Http/Models/request/front"
	utils "hft/Http/Utils"
	"hft/e"
	"hft/global"
	"strconv"
	"strings"
)

type Arc struct{}

func (*Arc) GetArc(paginate *front.ArcPage, city int) (page *utils.Page, err error) {

	var region *admin.Region

	err = global.OC_DB.First(&region, city).Error

	if err != nil {
		return nil, errors.New(e.RegionNotFound)
	}

	var arcList = make([]*front.ArcList, 0)
	var arcs []*admin.ArticleBase
	var ids = make([]int, 0)
	var strArr []string
	if paginate.Type != "" {
		strArr = strings.Split(paginate.Type, ",")
		if len(strArr) != 0 {
			for _, v := range strArr {
				id, _ := strconv.Atoi(v)
				ids = append(ids, id)
			}
		}
	}
	global.OC_DB.Scopes(daoFront.ArcDao.List(paginate, fmt.Sprintf("%v%v,%%", region.Link, region.ID), ids, global.OC_DB)).Find(&arcs).Scopes(dao.GetCount(global.OC_DB)).Count(&paginate.Total)
	for _, v := range arcs {
		arcList = append(arcList, &front.ArcList{Name: v.Name, Cover: v.Cover, Author: v.Author, ID: v.ID, Cont: v.PureText, CreateTime: v.CreateTime})
	}

	paginate.Data = arcList

	return &paginate.Page, nil
}

func (*Arc) GetArcInfo(id int) (data *front.ArcInfo, err error) {

	var activeCont *admin.ArticleBase
	err = global.OC_DB.Preload("Cont").First(&activeCont, id).Error
	if err != nil {
		return nil, errors.New(e.ArcNotExist)
	}
	var ids *front.IDS
	var activeID *admin.ArticleBase
	global.OC_DB.Raw(fmt.Sprintf("SELECT  (SELECT id FROM hft_article_base WHERE id > %v ORDER BY id LIMIT 1) AS next_id, (SELECT id FROM hft_article_base WHERE id < %v ORDER BY id DESC LIMIT 1) AS prev_id FROM hft_article_base WHERE (id = %v AND region_link = '%v')", id, id, id, activeCont.RegionLink)).Scan(&ids)

	if ids.PrevID == 0 {

		global.OC_DB.Model(&admin.ArticleBase{}).Select("id").Order("id DESC").Limit(1).Scan(&activeID)
		ids.PrevID = activeID.ID
	}
	if ids.NextID == 0 {
		global.OC_DB.Model(&admin.ArticleBase{}).Select("id").Order("id ASC").Limit(1).Scan(&activeID)
		ids.NextID = activeID.ID
	}
	var active = &front.ArcInfo{
		Author:     activeCont.Author,
		Title:      activeCont.Name,
		Cont:       activeCont.Cont.Content,
		ID:         activeCont.ID,
		PreID:      ids.PrevID,
		NextID:     ids.NextID,
		Group:      activeCont.ArtType,
		CreateTime: int(activeCont.CreateTime.UnixMilli()),
	}

	return active, nil

}

var ArcService = new(Arc)
